<template>
	<view v-if="!isFirstload" class="container">
		<!-- 页面头部 platform：当前终端(全局混入变量) -->
		<view class="main-header"
			:style="{ height: platform == 'H5' ? '260rpx' : '320rpx', paddingTop: platform == 'H5' ? '0' : '80rpx' }">
			<image class="bg-image" src="/static/background/user-header2.png" mode="scaleToFill" />

			<!-- 用户信息 -->
			<view class="user-info" v-if="isLogin">
				<view class="user-avatar">
          <!-- 用户头像 -->
					<avatar-image :url="userInfo.avatar_url" :width="100" />
				</view>

				<view class="user-content">
					<!-- 会员昵称 -->
					<view class="nick-name oneline-hide">{{ userInfo.nick_name }}</view>

					<!-- 会员等级 -->
					<view v-if="userInfo.grade_id > 0 && userInfo.grade" class="user-grade">
						<view class="user-grade_icon">
							<image class="image"
								src="" />
						</view>

						<view class="user-grade_name">
							<text>{{ userInfo.grade.name }}</text>
						</view>
					</view>

					<!-- 会员无等级时显示手机号 -->
					<view v-else class="mobile">{{ userInfo.mobile }}</view>
				</view>
			</view>

			<!-- 未登录 -->
			<view v-else class="user-info" @click="handleLogin">
				<view class="user-avatar">
					<avatar-image :width="100" />
				</view>

				<view class="user-content">
					<view class="nick-name">未登录</view>
					<view class="login-tips">点击登录账号</view>
				</view>
			</view>
		</view>

		<!-- 我的钱包 -->
		<view class="my-asset">
			<!-- 账户余额、积分、优惠券 -->
			<view class="asset-left flex-box dis-flex flex-x-around">
				<!-- 账户余额 -->
				<view class="asset-left-item" style="max-width: 200rpx;" @click="onTargetWallet">
					<view class="item-value dis-flex flex-x-center">
						<text>{{ isLogin ? assets.balance : '--' }}</text>
					</view>
					<view class="item-name dis-flex flex-x-center">
						<text class="oneline-hide">账户余额</text>
					</view>
				</view>

				<!-- 积分 -->
				<view class="asset-left-item" style="max-width: 200rpx;" @click="onTargetPoints">
					<view class="item-value dis-flex flex-x-center">
						<text>{{ isLogin ? assets.points : '--' }}</text>
					</view>
					<view class="item-name dis-flex flex-x-center">
						<text class="oneline-hide">{{ setting[SettingKeyEnum.POINTS.value].points_name }}</text>
					</view>
				</view>

				<!-- 优惠券 -->
				<view class="asset-left-item" style="max-width: 200rpx;" @click="onTargetMyCoupon">
					<view class="item-value dis-flex flex-x-center">
						<text>{{ isLogin ? assets.coupon : '--' }}</text>
					</view>
					<view class="item-name dis-flex flex-x-center">
						<text class="oneline-hide">优惠券</text>
					</view>
				</view>
			</view>

			<!-- 我的钱包 -->
			<view class="asset-right">
				<view class="asset-right-item" @click="onTargetWallet">
					<view class="item-icon dis-flex flex-x-center">
						<text class="iconfont icon-qianbao"></text>
					</view>
					<view class="item-name dis-flex flex-x-center">
						<text>我的钱包</text>
					</view>
				</view>
			</view>

		</view>

		<!-- 订单操作, 全部订单、待支付、待发货、待收货 -->
		<view class="order-navbar">
			<view class="order-navbar-item" v-for="(item, index) in orderNavbar" :key="index"
				@click="onTargetOrder(item)">
				<view class="item-icon">
					<text class="iconfont" :class="[`icon-${item.icon}`]"></text>
				</view>
				<view class="item-name">{{ item.name }}</view>
				<!-- 角标消息 -->
				<view class="item-badge" v-if="item.count && item.count > 0">
					<text v-if="item.count <= 99" class="text">{{ item.count }}</text>
					<text v-else class="text">99+</text>
				</view>
			</view>
		</view>

		<!-- 我的服务 -->
		<view class="my-service">
			<view class="service-title">我的服务</view>
			<view class="service-content clearfix">
				<block v-for="(item, index) in service" :key="index">
					<!-- 跳转页面 -->
					<view v-if="item.type == 'link'" class="service-item" @click="handleService(item)">
						<view class="item-icon">
							<text class="iconfont" :class="[`icon-${item.icon}`]"></text>
						</view>
						<view class="item-name">{{ item.name }}</view>
						<view class="item-badge" v-if="item.count && item.count > 0">
							<text v-if="item.count <= 99" class="text">{{ item.count }}</text>
							<text v-else class="text">99+</text>
						</view>
					</view>

					<!-- 非跳转页面操作 -->
					<view v-if="item.type == 'button' && platform == 'MP-WEIXIN'" class="service-item">
						<button class="btn-normal" :open-type="item.openType">
							<view class="item-icon">
								<text class="iconfont" :class="[`icon-${item.icon}`]"></text>
							</view>
							<view class="item-name">{{ item.name }}</view>
						</button>
					</view>
				</block>
			</view>
		</view>


		<!-- 退出登录 -->
		<view v-if="isLogin" class="my-logout">
			<view class="logout-btn" @click="handleLogout()">
				<text>退出登录</text>
			</view>
		</view>

	</view>
</template>

<script>
	import store from '@/store'
	import AvatarImage from '@/components/avatar-image'
	import {
		setCartTabBadge,
		checkLogin
	} from '@/core/app'
	import SettingKeyEnum from '@/common/enum/setting/Key'
	import SettingModel from '@/common/model/Setting'
	import * as UserApi from '@/api/user'
	import * as OrderApi from '@/api/order'

	// 订单操作
	const orderNavbar = [{
			id: 'all',
			name: '全部订单',
			icon: 'qpdingdan'
		},
		{
			id: 'payment',
			name: '待支付',
			icon: 'daifukuan',
			count: 0
		},
		{
			id: 'delivery',
			name: '待发货',
			icon: 'daifahuo',
			count: 0
		},
		{
			id: 'received',
			name: '待收货',
			icon: 'daishouhuo',
			count: 0
		},
	]

	/**
	 * 我的服务
	 * id: 标识; name: 标题名称; icon: 图标; type 类型(link和button); url: 跳转的链接
	 */
	const service = [{
			id: 'address',
			name: '收货地址',
			icon: 'shouhuodizhi',
			type: 'link',
			url: 'pages/address/index'
		},
		{
			id: 'coupon',
			name: '领券中心',
			icon: 'lingquan',
			type: 'link',
			url: 'pages/coupon/index'
		},
		{
			id: 'myCoupon',
			name: '优惠券',
			icon: 'youhuiquan',
			type: 'link',
			url: 'pages/my-coupon/index'
		},
		{
			id: 'help',
			name: '我的帮助',
			icon: 'bangzhu',
			type: 'link',
			url: 'pages/help/index'
		},
		{
			id: 'contact',
			name: '在线客服',
			icon: 'kefu',
			type: 'button',
			openType: 'contact'
		},
		{
			id: 'points',
			name: '我的积分',
			icon: 'jifen',
			type: 'link',
			url: 'pages/points/log'
		},
		{
			id: 'refund',
			name: '退换/售后',
			icon: 'shouhou',
			type: 'link',
			url: 'pages/refund/index',
			count: 0
		},
	]

	export default {
		components: {
			AvatarImage
		},
		data() {
			return {
				// 枚举类
				SettingKeyEnum,
				// 加载
				loading: true,
				// 首次加载
				isFirstload: false,
				// 是否已经登录
				isLogin: false,
				// 系统设置
				setting: {},
				// 当前登录的用户信息
				userInfo: {},
				// 当前用户的账号资产 balance: 账户余额，points: 积分，coupon：优惠券
				assets: {
					balance: '--',
					points: '--',
					coupon: '--'
				},
				// 我的服务
				service,
				// 订单操作
				orderNavbar,
				// 当前用户待处理的订单数量 payment: 待付款，deliver：待发货，received：待收货
				todoCounts: {
					payment: 0,
					deliver: 0,
					received: 0
				},
			}
		},
		/**
		 * 生命周期函数-监听页面显示
		 */
		async onShow() {
			await this.onRefreshPage()
		},
		methods: {
			// 刷新页面
			onRefreshPage() {
				// 更新购物车角标
				setCartTabBadge()
				// 判断是否已经登录
				this.isLogin = checkLogin()
				// 获取页面数据
				this.getPageData()
				this.getUserInfo()
			},
			// 获取页面数据
			getPageData(callback) {
				const that = this
				this.loading = true
				Promise.all([that.getSetting(), that.getUserInfo(), that.getUserAssets(), that.getTodoCounts()])
					.then(res => {
						that.isFirstload = false
						// 初始化我的服务数据
						that.initService()
						// 初始化订单操作数据
						that.initOrderTabbar()
						// 执行回调函数
						callback && callback()
					})
					.catch(err => console.log('catch', err))
					.finally(() => that.loading = false)
			},
			// 初始化我的服务数据
			initService() {
				const that = this
				const newService = []
				service.forEach(item => {
					if(item.id === 'points') {
						item.name = '我的' + that.setting[SettingKeyEnum.POINTS.value].points_name
					}
					// 数据角标
					if(item.count != undefined) {
						item.count = that.todoCounts[item.id]
					}
					newService.push(item)
				})
				that.service = newService
			},
			// 初始化订单操作数据
			initOrderTabbar() {
				const that = this
				const newOrderNavbar = []
				orderNavbar.forEach(item => {
					if(item.count != undefined) {
						item.count = that.todoCounts[item.id]
					}
					newOrderNavbar.push(item)
				})
				that.orderNavbar = newOrderNavbar
			},
			/**
			 * 获取商城设置(全部)
			 */
			getSetting() {
				const that = this
				return new Promise((resolve, reject) => {
					SettingModel.data()
						.then(setting => {
							that.setting = setting
							resolve(setting)
						}).catch(reject)
				})
			},
			/**
			 * 获取当前用户信息
			 */
			getUserInfo() {
				const that = this
				return new Promise((resolve, reject) => {
					!that.isLogin ? resolve(null) : UserApi.info({}, {
							load: that.isFirstload
						})
						.then(res => {
							that.userInfo = res.data.userInfo
							resolve(that.userInfo)
						})
						.catch(err => {
							if (err.result && err.result.status == 401) {
								that.isLogin = false
								resolve(null)
							} else {
								reject(err)
							}
						})
				})
			},
			/**
			 * 获取当前用户账户资产
			 */
			getUserAssets() {
				const that = this
				return new Promise((resolve, reject) => {
					!that.isLogin ? resolve(null) : UserApi.assets({}, {
							load: that.isFirstload
						})
						.then(res => {
							that.assets = res.data.assets
							resolve(that.assets)
						})
						.catch(err => {
							if (err.result && err.result.status == 401) {
								that.isLogin = false
								resolve(null)
							} else {
								reject(err)
							}
						})
				})
			},
			/**
			 * 获取当前用户带处理的订单数
			 */
			getTodoCounts() {
				const that = this
				return new Promise((resolve, reject) => {
					!that.isLogin ? resolve(null) : OrderApi.todoCounts({}, {
							load: that.isFirstload
						})
						.then(res => {
							that.todoCounts = res.data.counts
							resolve(that.todoCounts)
						})
						.catch(err => {
							if (err.result && err.result.status == 401) {
								that.isLogin = false
								resolve(null)
							} else {
								reject(err)
							}
						})
				})
			},
			// 用户未登录，点击登录事件
			handleLogin() {
				!this.isLogin && this.$navTo('pages/login/index')
			},

			// 我的钱包-跳转到账户余额页面
			onTargetWallet() {
				this.$navTo('pages/wallet/index')
			},

			// 跳转到我的积分页面
			onTargetPoints() {
				this.$navTo('pages/points/log')
			},

			// 跳转到我的优惠券页
			onTargetMyCoupon() {
				this.$navTo('pages/my-coupon/index')
			},

			// 跳转到订单页面
			onTargetOrder(item) {
				this.$navTo('pages/order/index', { dataType: item.id })
			},

			// 跳转到服务页面
			handleService({ url }) {
				this.$navTo(url)
			},

			// 退出登录
			handleLogout() {
				const that = this
				uni.showModal({
					title: '友情提示',
					content: '退出登录',
					success(res) {
						if(res.confirm) {
							store.dispatch('Logout', {})
								.then(res => {
									console.log('退出登录成功');
									that.onRefreshPage()
								})
								.catch(err => {
									console.log('退出登录失败', err);
								})
						}
					}
				})
			},
		},
		/**
		 * 下拉刷新
		*/
		onPullDownRefresh() {
			// 获取首页数据
			this.getPageData(() => {
				uni.showLoading({
					title: '加载中..',
					// 不允许点击遮罩层
					mask: true,
				})
				setTimeout(function() {
					uni.hideLoading()
					uni.stopPullDownRefresh()
				}, 500);
			})
		}
	}
</script>

<style lang="scss" scoped>
	// 页面头部
	.main-header {
		background-color: #fff;
		position: relative;
		width: 100%;
		height: 280rpx;
		background-size: 100% 100%;
		overflow: hidden;
		display: flex;
		align-items: center;
		padding-left: 30rpx;

		.bg-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 0;
		}

		.user-info {
			display: flex;
			height: 100rpx;
			z-index: 1;

			.user-content {
				display: flex;
				flex-direction: column;
				justify-content: center;
				margin-left: 30rpx;
				color: #c59a46;

				.nick-name {
					font-size: 34rpx;
					font-weight: bold;
					max-width: 270rpx;
				}

				.mobile {
					margin-top: 15rpx;
					font-size: 28rpx;
				}

				.user-grade {
					align-self: baseline;
					display: flex;
					align-items: center;
					background: #3c3c3c;
					margin-top: 12rpx;
					border-radius: 10rpx;
					padding: 4rpx 12rpx;

					.user-grade_icon .image {
						display: block;
						width: 32rpx;
						height: 32rpx;
					}

					.user-grade_name {
						margin-left: 5rpx;
						font-size: 26rpx;
						color: #EEE0C3;
					}

				}

				.login-tips {
					margin-top: 12rpx;
					font-size: 30rpx;
				}

			}
		}
	}

	// 角标组件
	.item-badge {
		position: absolute;
		top: 0;
		right: 55rpx;
		background: #fa2209;
		color: #fff;
		border-radius: 100%;
		min-width: 38rpx;
		height: 38rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 1rpx;
		font-size: 24rpx;
	}

	// 我的钱包
	.my-asset {
		display: flex;
		background: #fff;
		padding: 40rpx 0;

		.asset-right {
			width: 200rpx;
			border-left: 1rpx solid #eee;
		}

		.asset-right-item {
			text-align: center;
			color: #545454;

			.item-icon {
				font-size: 44rpx;
			}

			.item-name {
				margin-top: 14rpx;
				font-size: 28rpx;
			}

		}

		.asset-left-item {
			max-width: 183rpx;
			text-align: center;
			color: #666;
			padding: 0 16rpx;

			.item-value {
				font-size: 34rpx;
				color: red;
			}

			.item-name {
				margin-top: 6rpx;
			}

			.item-name {
				margin-top: 14rpx;
				font-size: 28rpx;
			}
		}

	}

	// 订单操作
	.order-navbar {
		display: flex;
		margin: 20rpx auto 20rpx auto;
		padding: 20rpx 0;
		width: 94%;
		box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
		font-size: 30rpx;
		border-radius: 5rpx;
		background: #fff;

		&-item {
			position: relative;
			width: 25%;

			.item-icon {
				text-align: center;
				margin: 0 auto;
				padding: 10rpx 0;
				color: #545454;
				font-size: 44rpx;
			}

			.item-name {
				font-size: 28rpx;
				color: #545454;
				text-align: center;
				margin-right: 10rpx;
			}

		}
	}

	// 我的服务
	.my-service {
		margin: 22rpx auto 22rpx auto;
		padding: 22rpx 0;
		width: 94%;
		box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
		border-radius: 5rpx;
		background: #fff;

		.service-title {
			padding-left: 24rpx;
			margin-bottom: 20rpx;
			font-size: 30rpx;
		}

		.service-content {

			margin-bottom: -20rpx;

			.service-item {
				position: relative;
				width: 25%;
				float: left;
				margin-bottom: 30rpx;

				.item-icon {
					text-align: center;
					margin: 0 auto;
					padding: 14rpx 0;
					color: #ff3800;
					font-size: 44rpx;
				}

				.item-name {
					font-size: 28rpx;
					color: #545454;
					text-align: center;
					margin-right: 10rpx;
				}

			}
		}
	}

	// 退出登录
	.my-logout {
		display: flex;
		justify-content: center;
		margin-top: 50rpx;

		.logout-btn {
			width: 80%;
			height: 86rpx;
			background: linear-gradient(to right, #ecb53c, #ff9211);
			color: #fff;
			margin: 0 auto;
			font-size: 28rpx;
			border-radius: 50rpx;
			border: 1px solid #dcdcdc;
			padding: 16rpx 0;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>
